package net.wicp.tams.common.binlog.self.bean;






import lombok.AccessLevel;
import lombok.Data;
import lombok.Setter;
import net.wicp.tams.common.binlog.self.IEventRead;
import net.wicp.tams.common.binlog.self.LogBuffer;
import net.wicp.tams.common.binlog.self.constant.Checksum;
import net.wicp.tams.common.binlog.self.constant.EventFlag;
import net.wicp.tams.common.binlog.self.constant.EventType;

/***
 * 事件执行时需要的Bean
 * 
 * @author andy.zhou
 *
 */
@Data
public class EventBean {
	private EventHeader head;// 事件头
	private LogBuffer body;// 事件体
	@Setter(AccessLevel.PRIVATE)
	private IEventRead eventRead;// 事件解析器
	@Setter(AccessLevel.PRIVATE)
	private long beginHead;// 事件头开始位置
	private String fileName;
	private String gtids;
	private Checksum checksum;

	public IEventRead getEventRead() {
		if (head == null || head.getEventType() == null) {
			return null;
		}
		if (eventRead == null) {
			eventRead = head.getEventType().newInstNoReflect(this);
		}
		return eventRead;
	}

	/***
	 * 事件头位置
	 * 
	 * @return
	 */
	public long getBeginHead() {
		if (beginHead == 0) {
			beginHead = head.getNextEventPos() - head.getEventSize();
		}
		return beginHead;
	}

	/***
	 * 事件体位置
	 * 
	 * @return
	 */
	public long getBeginBody() {
		return getBeginHead() + 19;
	}

	public EventBean(EventHeader head, byte[] body) {
		this.head = head;
		this.body = new LogBuffer(body, 0, body.length);
	}

	public EventBean(LogBuffer logBuffer) {
		// AssitRead assit = new AssitRead(eventBytes);
		logBuffer.forward(1);// 包的mark
		long timestamp = logBuffer.getInt32();// ByteUtil.readLongL(assit.readBytes(4));
		EventType eventType = EventType.get(logBuffer.getUint8());
		long serverId = logBuffer.getInt32();// ByteUtil.readLongL(assit.readBytes(4));
		long eventSize = logBuffer.getInt32();// ByteUtil.readLongL(assit.readBytes(4));
		long nextEventPos = logBuffer.getInt32();// ByteUtil.readLongL(assit.readBytes(4));
		EventFlag eventFlag = EventFlag.get(logBuffer.getUint16());

		this.body = logBuffer;
		this.head = EventHeader.builder().timestamp(timestamp).eventType(eventType).serverId(serverId)
				.eventSize(eventSize).nextEventPos(nextEventPos).eventFlag(eventFlag).build();
	}

}
